package com.example.repository.impl;

import com.example.entity.Student;
import com.example.repository.HibernateStudentRepository;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.SessionHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.List;

@Repository
public class HibernateStudentRepositoryImpl implements HibernateStudentRepository {

    private SessionFactory sessionFactory;

    public HibernateStudentRepositoryImpl(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }

    private Session currentSession(){
        //  SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.getResource(sessionFactory);
        //  return sessionHolder.getSession();
        Session session = sessionFactory.getCurrentSession();
        return session;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void save(Student student) {
        currentSession().save(student);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Student getById(Integer id) {
        return currentSession().get(Student.class, id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public List<Student> findByProperty(String property, Object value) {
        StringBuilder hql = new StringBuilder("from Student where ").append(property).append("=?1");
        Query query = currentSession().createQuery(hql.toString());
        query.setParameter(1, value);
        return query.list();
    }
}
